package controller

import (
	"fmt"
	"gitee.com/zhucheer/orange/app"
	"gitee.com/zhucheer/orange/captcha"
	"gitee.com/zhucheer/orange/database"
	"time"
)

func Welcome(c *app.Context) error {


	c.ResponseHeader().Set("Content-Type", "application/text")

	return c.ToString("orange is a fast api framework")
}

func AppDefer(c *app.Context)error{
	stopSig := make( chan app.StopSignal, 1)
	go app.ListenStop(stopSig)

	go func() {
		select {
		case <-stopSig:
			fmt.Println("stopSign====>")
		}
	}()

	go app.ExitWaitFunDo(func() {
		for i:=0;i<10;i++{
			fmt.Println("===>", i)
			time.Sleep(time.Second)
		}
	})

	app.AppDefer(func() {
		fmt.Println("app defer controller do")
	})

	return c.ToString("orange app shutdown wait proc done")
}

func AuthCheck(c *app.Context) error {

	return c.ToJson(map[string]interface{}{
		"auth": "auth is ok",
	})
}

func Test(c *app.Context) error {

	req := struct {
		VideoLink string `json:"videoLink"`
	}{}
	err := c.ParseForm(&req)

	fmt.Println(req)
	if err != nil {
		return c.ToJson(map[string]interface{}{
			"msg": "参数解析错误",
		})
	}
	return c.ToJson(map[string]interface{}{
		"test": "123",
	})
}

func Upload(c *app.Context) error {

	path, err := c.AppUpload("usfile")

	if err != nil {
		return c.ToString(err.Error())
	}

	return c.ToJson(map[string]interface{}{
		"info": "upload success",
		"path": path,
	})
}

func Captcha(c *app.Context) error {
	return captcha.CaptchaImgShow(c, 4)
}

func VerifyImg(c *app.Context) error {
	code := c.Request().FormValue("code")

	fmt.Println(code)

	ret:= captcha.CaptchaVerify(c, code)

	return c.ToJson(map[string]interface{}{
		"result": ret,
	})
}

type WxUsers struct {
	ID   uint   `gorm:"primary_key"`
	Name string `gorm:"nick_name"`
} // 默认表名是`users`
func SelectMySql(c *app.Context) error {
	db, put, err := database.GetMysql("default")
	defer func() {
		fmt.Println("put conn====>")
		database.PutConn(put)
	}()

	if err != nil {
		fmt.Println("db connect error", err)
		return nil
	}

	info := &WxUsers{}
	db.Table("qi_user").Where("id > ?", "1").First(&info)
	fmt.Println("db find====")

	return c.ToJson(map[string]interface{}{
		"result": "select success",
	})
}

func SelectRedis(c *app.Context) error {
	db, put, err := database.GetRedis("default")
	if err != nil {
		fmt.Println("db connect error", err)
		return nil
	}
	defer put()

	db.Do("SET", "tttx", "rrrrr")

	return c.ToJson(map[string]interface{}{
		"result": "select success",
	})
}
